package com.jmb.api.custom.interceptor;

import com.jmb.api.common.constant.RedisConstant;
import com.jmb.api.common.exception.LeaseException;
import com.jmb.api.common.result.ResultCodeEnum;
import com.jmb.api.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;
    /*
     * 拦截器，在请求处理之前进行调用（controller方法调用之前）
     * 校验token是否正确，约定header头中携带token
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        log.info("token:{}", token);
        Claims claims = JwtUtil.parseToken(token);
        String redisToken = redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY + claims.get(RedisConstant.USER_USERID_KEY));
        if (redisToken == null || !redisToken.equals(token)){
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRE);
        }
        return true;
    }
}
